//
//  DCFNetworkManager.m
//  DCF
//
//  Created by 吴文拼 on 2017/12/26.
//  Copyright © 2017年 吴文拼. All rights reserved.
//

#import "DCFNetworkManager.h"
#import "AFNetworking.h"
#import "NSString+GetDevice.h"
#import "DCFLoginManager.h"
#import "ServerAPISetting.h"
#import <CommonCrypto/CommonHMAC.h>

#define TIMEOUT_INTERVAL 10.0

@implementation DCFNetworkManager

+(void)workToSendHTTPRequestHeader:(AFHTTPRequestSerializer *)needRequest{
    
    needRequest.timeoutInterval = TIMEOUT_INTERVAL;
    
    [needRequest setValue:[NSString deviceVersion] forHTTPHeaderField:@"DC-DeviceType"];
    [needRequest setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forHTTPHeaderField:@"DC-AppVersion"];
    [needRequest setValue:@"iOS" forHTTPHeaderField:@"DC-OsType"];
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [needRequest setValue:idfv forHTTPHeaderField:@"DC-DeviceId"];
    [needRequest setValue:[[NSBundle mainBundle] bundleIdentifier] forHTTPHeaderField:@"DC-PackName"];
    [needRequest setValue:@"AppStore" forHTTPHeaderField:@"DC-StoreName"];
    if ([[DCFLoginManager sharedInstance] isLogin]) {
        [needRequest setValue:[NSString stringWithFormat:@"%@",[[DCFLoginManager sharedInstance] currentUser].userId] forHTTPHeaderField:@"DC-Uid"];
        [needRequest setValue:[NSString stringWithFormat:@"%@",[[DCFLoginManager sharedInstance] currentUser].token] forHTTPHeaderField:@"DC-Token"];
    }
}

+(void)giveHTTPRequestHeader:(NSMutableURLRequest *)needRequest{
    
    needRequest.timeoutInterval = TIMEOUT_INTERVAL;
    
    [needRequest setValue:[NSString deviceVersion] forHTTPHeaderField:@"DC-DeviceType"];
    [needRequest setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forHTTPHeaderField:@"DC-AppVersion"];
    [needRequest setValue:@"iOS" forHTTPHeaderField:@"DC-OsType"];
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [needRequest setValue:idfv forHTTPHeaderField:@"DC-DeviceId"];
    [needRequest setValue:[[NSBundle mainBundle] bundleIdentifier] forHTTPHeaderField:@"DC-PackName"];
    [needRequest setValue:@"AppStore" forHTTPHeaderField:@"DC-StoreName"];
    if ([[DCFLoginManager sharedInstance] isLogin]) {
        [needRequest setValue:[NSString stringWithFormat:@"%@",[[DCFLoginManager sharedInstance] currentUser].userId] forHTTPHeaderField:@"DC-Uid"];
        [needRequest setValue:[NSString stringWithFormat:@"%@",[[DCFLoginManager sharedInstance] currentUser].token] forHTTPHeaderField:@"DC-Token"];
    }
}

+(NSDictionary *)getHeaderDic{
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
    [mutDic setValue:[NSString deviceVersion] forKey:@"DeviceType"];
    [mutDic setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"AppVersion"];
    [mutDic setValue:@"iOS" forKey:@"OsType"];
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [mutDic setValue:idfv forKey:@"DeviceId"];
    [mutDic setValue:[[NSBundle mainBundle] bundleIdentifier] forKey:@"PackName"];
    [mutDic setValue:@"AppStore" forKey:@"StoreName"];
    if ([[DCFLoginManager sharedInstance] isLogin]) {
        [mutDic setValue:[NSString stringWithFormat:@"%@",[[DCFLoginManager sharedInstance] currentUser].userId] forKey:@"Uid"];
        [mutDic setValue:[NSString stringWithFormat:@"%@",[[DCFLoginManager sharedInstance] currentUser].token] forKey:@"Token"];
    }
    return [mutDic copy];
}


+ (void)postDCFTo:(NSString *)url withJSON:(id)parameters successHandler:(DCFNetworkSuccessHandler)successHandler failHandler:(DCFNetworkFailHandler)failHandler{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [self workToSendHTTPRequestHeader:manager.requestSerializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
    
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCFResponseModel *model = [[DCFResponseModel alloc] initWithResponse:responseObject];
        successHandler(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self checkFailShouldLogoutWithError:error failure:failHandler];
    }];
}

+ (void)deleteDCF:(NSString *)url withJSON:(id)parameters successHandler:(DCFNetworkSuccessHandler)successHandler failHandler:(DCFNetworkFailHandler)failHandler{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD",nil];
    [self workToSendHTTPRequestHeader:manager.requestSerializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
    [manager DELETE:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCFResponseModel *model = [[DCFResponseModel alloc] initWithResponse:responseObject];
        successHandler(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self checkFailShouldLogoutWithError:error failure:failHandler];
    }];
}

+ (void)fetchDCFJSONFrom:(NSString *)url successHandler:(DCFNetworkSuccessHandler)successHandler failHandler:(DCFNetworkFailHandler)failHandler{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [self workToSendHTTPRequestHeader:manager.requestSerializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCFResponseModel *model = [[DCFResponseModel alloc] initWithResponse:responseObject];
        successHandler(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self checkFailShouldLogoutWithError:error failure:failHandler];
    }];
}

+ (void)putDCFTo:(NSString *)url withJSON:(id)parameters successHandler:(DCFNetworkSuccessHandler)successHandler failHandler:(DCFNetworkFailHandler)failHandler{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [self workToSendHTTPRequestHeader:manager.requestSerializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
    [manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCFResponseModel *model = [[DCFResponseModel alloc] initWithResponse:responseObject];
        successHandler(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self checkFailShouldLogoutWithError:error failure:failHandler];
    }];
}

+ (void)fetchDCFJSONFrom:(NSString *)url withTimeoutInterval:(NSInteger)time successHandler:(DCFNetworkSuccessHandler)successHandler failHandler:(DCFNetworkFailHandler)failHandler{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [self workToSendHTTPRequestHeader:manager.requestSerializer];
    manager.requestSerializer.timeoutInterval = time;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCFResponseModel *model = [[DCFResponseModel alloc] initWithResponse:responseObject];
        successHandler(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self checkFailShouldLogoutWithError:error failure:failHandler];
    }];
}

//上传表单数据
+ (void)postDCFTo:(NSString *)url withJSON:(id)parameters uploadDataArr:(NSArray *)dataArr successHandler:(DCFNetworkSuccessHandler)successHandler failHandler:(DCFNetworkFailHandler)failHandler{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [self workToSendHTTPRequestHeader:manager.requestSerializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (DCFNetworkUploadDataModel *uploadParam in dataArr) {
            [formData appendPartWithFileData:uploadParam.fileData name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCFResponseModel *model = [[DCFResponseModel alloc] initWithResponse:responseObject];
        successHandler(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self checkFailShouldLogoutWithError:error failure:failHandler];
    }];
}

//检查错误是否为401
+(void)checkFailShouldLogoutWithError:(NSError *)error failure:(DCFNetworkFailHandler)failHandler{
    if ([error.localizedDescription rangeOfString:@"(401)"].location != NSNotFound&&[[DCFLoginManager sharedInstance] isLogin]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:DCF_NOTIFY_USER_401_SHOULD_RELOGIN object:nil];
    }else{
        failHandler(error);
    }
}



@end

@implementation DCFResponseModel

-(instancetype)initWithResponse:(NSDictionary *)response{
    if (self = [super init]) {
        self.statusCode = [response[@"code"] integerValue];
        self.responseData = response[@"data"]&&![response[@"data"] isEqual:[NSNull null]]?response[@"data"]:nil;
        self.message = response[@"message"];
        self.success = [response[@"success"] boolValue];
        self.originalData = response;
    }
    return self;
}

@end

@implementation DCFNetworkUploadDataModel


@end
